#ifndef F7CC1367_5D66_421E_8D94_98781A7684CC
#define F7CC1367_5D66_421E_8D94_98781A7684CC

#include<iostream>
#include"Log.hpp"

#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<cstring>

enum
{
    SockErr = 2,
    BindErr,
    ListenErr,
};

const int backlog = 10;


class Socket
{
public:
    Socket(){}
    ~Socket(){}
public:
    void SocketInit()
    {
        sockfd = socket(AF_INET, SOCK_STREAM, 0);  //创建套接字
        if (sockfd < 0)
        {
            lg(Fatal, "socket error...");
            exit(SockErr);
        }
    }
    
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;  //绑定本地主机和端口号， 也就是启动服务器的时候的绑定的各种信息
        memset(&local, 0, sizeof(local));
        //
        local.sin_family = AF_INET;
        local.sin_port = htons(port); //主机序列转网络序列
        local.sin_addr.s_addr = INADDR_ANY;
        //
        if (bind(sockfd, (sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error");
            exit(BindErr);
        }
    }

    void Listen()
    {
        //设置监听状态:
        if (listen(sockfd, backlog) < 0)
        {
            lg(Fatal, "listen error");
            exit(ListenErr);
        }
    }

    int Accpet(string* clientip, uint16_t* clientport)
    {
        //创建套接字结构体
        struct sockaddr_in client;
        socklen_t len = sizeof(client);

        //接受客户端套接字
        int newfd = accept(sockfd, (sockaddr*)&client, &len);
        if (newfd < 0) 
        {
            lg(Waring, "accept error");
            return -1;
        }
        
        //将套接字里面的数据带出去， 端口号和IP地址        
        char bufip[64];
        memset(bufip, 0, sizeof(bufip));
        inet_ntop(AF_INET, &client.sin_addr, bufip, sizeof(bufip));
        *clientip = bufip;
        *clientport = ntohs(client.sin_port);
        return newfd;
    }

    bool Connect(string serverip, uint16_t serverport)
    {
        sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
        connect(sockfd, (sockaddr*)&server, sizeof(server));
        return true;
    }

    void Close()
    {
        close(sockfd);
    }

    int Fd()
    {
        return sockfd; 
    }


private:
    int sockfd;
};




#endif /* F7CC1367_5D66_421E_8D94_98781A7684CC */
